package com.mindao.app.site.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mindao.app.common.spring.controller.BaseController;
import com.mindao.app.common.spring.model.BaseModel;
import com.mindao.app.common.spring.page.Pagination;
import com.mindao.app.common.spring.service.util.JsonResult;
import com.mindao.app.ea.service.UserService;
import com.mindao.app.site.model.Event;
import com.mindao.app.site.model.EventEnroll;
import com.mindao.app.site.service.EventService;
import com.mindao.app.site.util.SiteConstants;
import com.mindao.utils.config.EaCommonUtils;
import com.mindao.utils.config.EaConstant;

/**
/* 版权所有： 广州敏道科技有限公司
/*
/* 功能描述：
/*
/* 创 建 人：李国才
/* 创建时间：2016年6月16日 下午1:03:24 	
 **/
@Controller
@RequestMapping("/site/event")
public class EventController extends BaseController<Event> {
	@Autowired
	protected UserService userService;
	
	@Autowired
	protected EventService eventService;
	
 
	
	private final Logger log = LoggerFactory.getLogger(EventController.class);
	private static final DateFormat SIMPLE_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
	
	/** 初始化文本日期数据进行绑定 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, "deadline", new CustomDateEditor(SIMPLE_DATE_FORMATER, Boolean.TRUE));
		binder.registerCustomEditor(Date.class, "createTime", new CustomDateEditor(SIMPLE_DATE_FORMATER, Boolean.TRUE));
	}
	
	/**
	 * 加载分页列表数据
	 * @param request
	 * @param response
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */
	@Override
	@RequestMapping( method = RequestMethod.POST)
	public String searchPageAjax(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs) throws Exception {
		String className =  getModelClass().getName();
		Long rootOrgId=userService.getRootOrgIdByUserId((Long) session.getAttribute(EaConstant.SESSION_USER_ID));
		String sql="from " + className + "   where status>"+BaseModel.STATUS_REMOVED +" and rootOrganizeId="+rootOrgId;
		Map map=request.getParameterMap();
        //按页面提交参数分页查询 
		Pagination p= getPagination( );
		List<Event> list=null;
		try {
			list =(List<Event> ) baseService.findByHQLPage(sql, map, "", getParameter("orderBy"),p );
			for (Event event : list) {
				rhs.addAttribute("enrollable_"+event.getId(), eventService.getEnrollable(event));
			}
			rhs.addAttribute("dataList", list);
			rhs.addAttribute("pagination", p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(),e);
		}
		return rtnDefault(request, response, session, rhs);
	}

	
	/**
	 * 根据uuid保存数据，保存后返回列表页面
	 * @param request
	 * @param response
	 * @param session
	 * @param rhs
	 * @param uuid
	 * @return
	 * @throws Exception
	 */
	@Override
	@RequestMapping( method = RequestMethod.POST)
	public String saveByUuid(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs, Event obj) throws Exception {
		String className = getModelClass().getName();
 
		Long rootOrgId=userService.getRootOrgIdByUserId((Long) session.getAttribute(EaConstant.SESSION_USER_ID));
		obj.setRootOrganizeId(rootOrgId);
		if (obj.getSubjects()!=null){
			obj.setSubjects(obj.getSubjects().replaceAll("，", ","));
		}
		if (obj.getUuid() == null || obj.getUuid().toString().equals("")) { // create
			baseService.create(obj);
		} else { // edit
			obj.setId(EaCommonUtils.getObjectIdByUUID( obj.getUuid(),className ));
			baseService.update(obj);
		}
		//重新定向list,避免页面重复刷新
		return redirectToSearch(request,response,"saveByUuid");
	}
	
	/**
	 * 进入报名页面
	 * @param request
	 * @param response
	 * @param session
	 * @param rhs
	 * @return
	 * @throws Exception
	 */

	@RequestMapping   
	public String eventEnroll(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs) throws Exception {
		String uuid=getpara("uuid");
		Event event=null;
		if (uuid.length()==0){
			 event=eventService.getCurrentEvent();
		}else{
			 event=(Event)EaCommonUtils.getObjectByUuid(uuid, "Event");
		}
		if (event==null){
			rhs.addAttribute("msg", "没有进行中的活动");
			return super.rtnGlobalBusinessError(request, response, session, rhs);
		}else{
			rhs.addAttribute("obj", event);
			EventEnroll enroll= eventService.getEventEnroll(event.getId(), super.getCurrentUserId(), (String)EaCommonUtils.getSessionObject(SiteConstants.SESSION_OPENID));
			rhs.addAttribute("enroll", enroll);
			
			rhs.addAttribute("enrollable", eventService.getEnrollable(event));
			return super.rtnDefault(request, response, session, rhs);
		}
	}
	
	@ResponseBody
	@RequestMapping  ( method = RequestMethod.POST) 
	public JsonResult submitEnroll(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs,EventEnroll enroll) throws Exception {
		//后台参数检查，避免前台禁止脚本来攻击
		boolean flag=true;
		if (flag && StringUtils.isBlank(getpara("name"))){
			flag=false;
		}
		if (flag && StringUtils.isBlank(getpara("qq"))){
			flag=false;
		}
		String  enrollSubjects =getParameter("enrollSubjects");
		if (flag && enrollSubjects!=null &&enrollSubjects.length()==0){
			flag=false;
		}
		if (!flag ){
			JsonResult jrErr=new JsonResult(JsonResult.ERROR,"参数不完整");
			return jrErr;
		}

		//后台防攻击检查todo
		
		String uuid=getpara("eventUuid");
		Event event=(Event)EaCommonUtils.getObjectByUuid(uuid, "Event");
		if (!eventService.getEnrollable(event)){
			JsonResult jrErr=new JsonResult(JsonResult.ERROR,"报名时间已结束");
			return jrErr;
		}
		
		String enrollUuid=getpara("enrollUuid");
		if (!StringUtils.isBlank(enrollUuid)){
			enroll=(EventEnroll)EaCommonUtils.getObjectByUuid(enrollUuid, "EventEnroll");
			enroll.setName(getpara("name"));
			enroll.setQq(getpara("qq"));
			enroll.setEnrollSubjects(getpara("enrollSubjects"));
		}else{
			//enroll.setEnrollDate(new Date());
		}
		String openid=(String)EaCommonUtils.getSessionObject(SiteConstants.SESSION_OPENID);
		if (openid!=null){
			enroll.setOpenid(openid);
			enroll.setNickname((String)EaCommonUtils.getSessionObject(SiteConstants.SESSION_NICKNAME));
		}
		enroll.setEvent(event); 
		enroll.setDisabled(EventEnroll.DISABLED_FALSE);
		enroll.setUserId(super.getCurrentUserId());
		if (!StringUtils.isBlank(enrollUuid)){
			baseService.update(enroll);
		}else{
			baseService.create(enroll);
		}
 
	     
		JsonResult jrSucc=new JsonResult(JsonResult.SUCCESS,"报名成功");
		return jrSucc;
	}
	
	@ResponseBody
	@RequestMapping  ( method = RequestMethod.POST) 
	public JsonResult cancelEnroll(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs,String enrollUuid) throws Exception {
		EventEnroll  enroll=(EventEnroll)EaCommonUtils.getObjectByUuid(enrollUuid, "EventEnroll");
		enroll.setDisabled(EventEnroll.DISABLED_TRUE);
		baseService.update(enroll);
		JsonResult jrSucc=new JsonResult(JsonResult.SUCCESS,"取消报名成功");
		return jrSucc;
	}
}
